package com.itboye.hutouben.activity.driverrepair.fragment;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.ant.liao.GifView;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.itboye.hutouben.R;
import com.itboye.hutouben.activity.driverrepair.DriverRepair;
import com.itboye.hutouben.activity.driverrepair.MapActivity;
import com.itboye.hutouben.activity.mysetting.SettingActivity;
import com.itboye.hutouben.adapter.SpingAdapter;
import com.itboye.hutouben.base.BaseFragment;
import com.itboye.hutouben.base.MyApplcation;
import com.itboye.hutouben.base.ptr.BasePtr;
import com.itboye.hutouben.bean.RepairBean;
import com.itboye.hutouben.bean.UplodeImg;
import com.itboye.hutouben.bean.WeiXiuBeans;
import com.itboye.hutouben.choosecity.db.DBManager;
import com.itboye.hutouben.db.CitysBean;
import com.itboye.hutouben.photo.CopyOfPhotoActivity;
import com.itboye.hutouben.presenter.HomeMallPresenter;
import com.itboye.hutouben.presenter.SysTemMessgelPresenter;
import com.itboye.hutouben.util.ByAlert;
import com.itboye.hutouben.util.CameraPopupWindow;
import com.itboye.hutouben.util.Const;
import com.itboye.hutouben.util.GlideLoader;
import com.itboye.hutouben.util.ImageCompress;
import com.itboye.hutouben.util.IsUtilUid;
import com.itboye.hutouben.util.ListToStringUtil;
import com.itboye.hutouben.util.MultipartRequest;
import com.itboye.hutouben.util.MyTask;
import com.itboye.hutouben.util.MyTimerFormat;
import com.itboye.hutouben.util.SPUtils;
import com.itboye.hutouben.util.TimeFormat;
import com.itboye.hutouben.util.XImageLoader;
import com.itboye.hutouben.volley.ResultEntity;
import com.itboye.hutouben.widget.XGridView;
import com.yancy.imageselector.ImageConfig;
import com.yancy.imageselector.ImageSelector;
import com.yancy.imageselector.ImageSelectorActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;
import java.util.Timer;
import java.util.TimerTask;

import in.srain.cube.views.ptr.PtrDefaultHandler2;
import in.srain.cube.views.ptr.PtrFrameLayout;

import static com.itboye.hutouben.util.SPUtils.getSp;

/**
 * 报修界面
 */
@SuppressLint("ValidFragment")
public class RepairTvFragment extends BaseFragment implements Observer, TextWatcher {

    ImageView my_animal;
    TextView tv;
    AnimationDrawable drawable;
    TextView wait_tv, ad_tv;
    int i = 0;
    RelativeLayout busy_rel;//当前订单未完成界面
    RelativeLayout add_repair_rel;//立即报修界面
    RelativeLayout dispatch_rel;//派单中界面
    EditText type_tv, phone_tv, car_type_tv, detail_tv;
    ImageView map_img, type_img, null_order_img;
    static EditText address_tv;
    TextView ok;//立即报修ok
    TextView null_order_text, tvwerwerwerwer;

    Spinner spinner1, spinner21;

    HomeMallPresenter presenter;
    SysTemMessgelPresenter messgelPresenter;

    WeiXiuBeans weixiubean;
    SpingAdapter adapter;
    String vehicle_type;
    String repair_type;
    String city;
    String area;
    private DBManager dbManager;
    private SQLiteDatabase database;
    private ArrayList<CitysBean> litCity;
    private ListToStringUtil stringUtil;
    PtrFrameLayout commend_anchor_ptr;
    private LocationClient locClient;
    CitysBean bean;
    Cursor cursor;
    String cityCodeId;

    private GifView gif;
    RepairBean beans;

    int RESULT_OK = -1;
    String uid;
    ViewGroup imgContainer;

    XGridView noScrollgridview;
    private GridAdapter adapters;
    RelativeLayout address_rel;

    public static List<String> listImg = new ArrayList<String>();//保存图片
    StringBuffer sb = new StringBuffer();//保存图片id
    protected StringBuffer imgBuffer = new StringBuffer();//上传成功的图片id
    /**
     * 时间差
     */
    int shicha;
    String phone = "";
    private CameraPopupWindow cameraPopupWindow;
    Timer timer;

    //选择位置出来的横纵坐标
    private String lngg="";
    private String latt="";

    //定位出来的横纵坐标
    public  Double lat;
    public  Double lng;

    RepairTvFragment con;

    @Override
    public int initView() {
        return R.layout.fragment_repair_tv;
    }

    @Override
    public void onMyActivityCreated() {
        con=this;
        uid = getSp(getActivity(), Const.ID);
        BasePtr.setPagedPtrStyle(commend_anchor_ptr);//设置上拉下拉刷新
        my_animal.setBackgroundResource(R.drawable.my_animation);
        drawable = (AnimationDrawable) my_animal.getBackground();
        weixiubean = new WeiXiuBeans();
        bean = new CitysBean();
        litCity = new ArrayList<CitysBean>();
        presenter = new HomeMallPresenter(this);
        presenter.onRepair();
        phone = SPUtils.get(getActivity(), null, Const.MOBILE, "") + "";
        phone_tv.setText(phone);
        city = getActivity().getIntent().getStringExtra("city");
        Log.d("citycitycity", city + "");
        address_tv.addTextChangedListener(this);
        dbManager = new DBManager(getActivity());
        dbManager.openDateBase();
        database = SQLiteDatabase.openOrCreateDatabase(DBManager.DB_PATH + "/"
                + DBManager.DB_NAME, null);

        beans = new RepairBean();
        messgelPresenter = new SysTemMessgelPresenter(this);
        messgelPresenter.onByRepairCurrent(uid, "6");

        gif = (GifView) getActivity().findViewById(R.id.gif);
        gif.setGifImage(R.drawable.ig);

        showProgressDialog("数据加载中...", true);

        timer = new Timer();

        commend_anchor_ptr.setPtrHandler(new PtrDefaultHandler2() {
            @Override
            public void onLoadMoreBegin(PtrFrameLayout frame) {
                uid = getSp(getActivity(), Const.ID);
                messgelPresenter.onByRepairCurrent(uid, "6");
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                uid = getSp(getActivity(), Const.ID);
                messgelPresenter.onByRepairCurrent(uid, "6");
            }
        });
        commend_anchor_ptr.autoRefresh();

        isCameraPermission(getActivity(), 1);
        InitLocation();
        locClient.start();

        IntentFilter intentFilterExit = new IntentFilter("presenter");
        getActivity().registerReceiver(nichengBroadcastReceiver, intentFilterExit);
        // 维修结束
        IntentFilter filter1 = new IntentFilter("weixiu");
        getActivity().registerReceiver(emailBroadcastReceiver, filter1);
        //登录的广播
        IntentFilter filter = new IntentFilter(SettingActivity.EXITCHANGE);
        getActivity().registerReceiver(loginReceiver, filter);

        noScrollgridviews();
    }
    BroadcastReceiver loginReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            uid = getSp(getActivity(), Const.ID);
            messgelPresenter.onByRepairCurrent(uid, "6");

            String phone = SPUtils.get(getActivity(), null, Const.MOBILE, "") + "";
            phone_tv.setText(phone);
        };
    };
    BroadcastReceiver emailBroadcastReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            messgelPresenter.onByRepairCurrent(uid, "6");
        }

        ;
    };
    BroadcastReceiver nichengBroadcastReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            timeCount();
            messgelPresenter.onByRepairCurrent(uid, "6");
            presenter.onRepair();
        }
    };
    //操作gridview
    private void noScrollgridviews() {
        noScrollgridview = (XGridView) getActivity().findViewById(R.id.noScrollgridview);
        noScrollgridview.setSelector(new ColorDrawable(Color.TRANSPARENT));
        noScrollgridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                    long arg3) {
                if (arg2 == listImg.size()) {
                    pic();
                } else {
                    Intent intent = new Intent(getActivity(),
                            CopyOfPhotoActivity.class);
                    intent.putExtra("ID", arg2);
                    intent.putExtra("type", 1);
                    startActivityForResult(intent, 101);
                }
            }
        });
        adapters = new GridAdapter(getActivity());
        noScrollgridview.setAdapter(adapters);
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        if (cursor != null || database != null) {
            // cursor.close();
            database.close();
        }
        if (listImg != null) {
            listImg.clear();
        }
        getActivity().unregisterReceiver(nichengBroadcastReceiver);
        getActivity().unregisterReceiver(emailBroadcastReceiver);
        getActivity().unregisterReceiver(loginReceiver);
    }
    //6.0添加拍照的权限
    private static String[] PERMISSIONS_CAMERA_AND_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA};

    public static boolean isCameraPermission(Activity context, int requestCode) {
        if (Build.VERSION.SDK_INT >= 23) {
            int storagePermission = ActivityCompat.checkSelfPermission(context,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE);
            int cameraPermission = ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA);
            if (storagePermission != PackageManager.PERMISSION_GRANTED || cameraPermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(context, PERMISSIONS_CAMERA_AND_STORAGE,
                        requestCode);
                return false;
            }
        }
        return true;
    }



    @Override
    public void onStart() {
        super.onStart();
//        List<String> li = new ArrayList<>();
//        for (String s : listImg) {
//            li.add(ImageCompress.compress(s));
//        }
//        listImg.clear();
//        listImg.addAll(li);
        adapters= new GridAdapter(getActivity());
        noScrollgridview.setAdapter(adapters);
    }

    public void onStop() {
        // TODO Auto-generated method stub
        if (locClient != null) {
            locClient.stop();
        }
        super.onStop();
    }

    private void InitLocation() {
        locClient = new LocationClient(getActivity());
        locClient.registerLocationListener(new MyLocationListener());
        LocationClientOption option = new LocationClientOption();
        int span = 0;
        option.setScanSpan(span);//可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
        option.setOpenGps(true);// 打开gps
        option.setCoorType("bd09ll");// 设置坐标类型
        option.setAddrType("all");
        option.setScanSpan(1);//
        locClient.setLocOption(option);
        locClient.start();
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (address_tv.getText().toString().length() <= 0) {

        } else {
            try {
                if (city == null || city == "") {
//                    ByAlert.alert("请定位到当前位置");
                } else
                    getAreayCode(city);
                Log.d("citycity", city);
            } catch (Exception ex) {

            }
        }
    }

    @Override
    public void afterTextChanged(Editable s) {

    }

    /**
     * 实现实位回调监听
     */
    public class MyLocationListener implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            //Receive Location
            if(location!=null) {
                lat = location.getLatitude();
                lng = location.getLongitude();
            }
            StringBuffer sb = new StringBuffer(256);
            if (location.getLocType() == BDLocation.TypeNetWorkLocation) {
                sb.append(location.getAddrStr());
            }
//            LocationResult.setText(sb.toString());
            getAreayCode(location.getCity() + "");
            MyTask myTask = new MyTask();
            myTask.setTextView(address_tv);
            myTask.setAddress(sb.toString());
            myTask.execute();
//            address_tv.setText(sb.toString());
//            Log.i("dwtedx", sb.toString());

        }

        @Override
        public void onConnectHotSpotMessage(String s, int i) {

        }

    }

    /***
     * 查询
     * @param city
     * @return
     */
    private String getAreayCode(String city) {
        // TODO Auto-generated method stub
        String cityCode = null;
        if (city.equals("北京市") || city.equals("上海市") || city.equals("天津京市") || city.equals("重庆市")) {
            if (database != null)
                cursor = database.query("hat_province", new String[]{"provinceID"},
                        "province=?", new String[]{city}, null, null, null);
            if (cursor != null)
                while (cursor.moveToNext()) {
                    cityCode = cursor.getString(0);
                }
        } else if (database != null)
            cursor = database.query("hat_city", new String[]{"cityID"},
                    "city=?", new String[]{city}, null, null, null);
        if (cursor != null)
            while (cursor.moveToNext()) {
                cityCode = cursor.getString(0);
            }
        isDid(cityCode);
        System.out.println("cityIdcityId" + cityCode);
        cursor.close();
        return cityCode;
    }



    View.OnClickListener clickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.pick_image:
                    InitLocation();
                    locClient.start();
                    break;
                case R.id.open_camera:
                    Intent intent = new Intent(getActivity(), MapActivity.class);
                    startActivityForResult(intent, 108);
                    break;

            }
            cameraPopupWindow.dismiss();
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv:
                drawable.start();
                break;
            case R.id.map_img:
                cameraPopupWindow = new CameraPopupWindow(getActivity(), clickListener);
                cameraPopupWindow.showAtLocation(v, Gravity.BOTTOM
                        | Gravity.CENTER_HORIZONTAL, 0, 0);
                cameraPopupWindow.setTextTop("去地图选择");
                cameraPopupWindow.setTextBottom("定位");
//
                break;
            case R.id.address_rel:


                break;
            case R.id.ok:
                String phone = phone_tv.getText().toString();
                String detail = detail_tv.getText().toString();
                String address = address_tv.getText().toString();
                if (phone.equals("")) {
                    ByAlert.alert("请填写联系方式");
                    return;
                }
                if (detail.equals("")) {
                    ByAlert.alert("请填写描述");
                    return;
                }
                if (address.equals("")) {
                    ByAlert.alert("请填写或选择地址");
                    return;
                }
                showProgressDialog("请稍后...", false);
                List<File> files = new ArrayList<File>();
                for (i = 0; i < listImg.size(); i++) {
                    File file = new File(listImg.get(i));
                    files.add(file);
                }
                if (files.size() <= 0) {
                    // ByAlert.alert("请上传图片");
                    presenter.onRadRescus(uid, phone, address, detail, vehicle_type + "", "", "",lngg.equals("")?lng+"":lngg,latt.equals("")?lat+"":latt);
                    return;
                }
                Map<String, String> params = new HashMap<String, String>();
                params.put("uid", uid);
                params.put("type", "other");
                MultipartRequest multipartRequest = new MultipartRequest(
                        Const.IMAGE_URL,
                        new Response.Listener<String>() {

                            @Override
                            public void onResponse(String arg0) {
                                // TODO Auto-generated method stub
                                String code = "";
                                String result = "";
                                try {
                                    closeProgressDialog();
                                } catch (Exception e) {

                                }
                                try {
                                    JSONObject jsonObject = new JSONObject(arg0);
                                    code = jsonObject.getString("code");
                                    result = jsonObject.getString("data");
                                    if (code.equals("-1")) {
                                        ByAlert.alert(result);
                                    } else {
                                        Gson gson = new Gson();
                                        Type type = new TypeToken<UplodeImg>() {
                                        }.getType();
                                        Log.v("msg", result + "多图上传");
                                        UplodeImg beans = gson.fromJson(
                                                arg0, type);
                                        for (UplodeImg.Dates bean : beans.getData()) {
                                            imgBuffer.append(bean.getId() + ",");
                                        }

                                        String tid = imgBuffer.substring(0, imgBuffer.length() - 1);

                                        String phone = phone_tv.getText().toString();
                                        String detail = detail_tv.getText().toString();
                                        String address = address_tv.getText().toString();
                                        //     presenter.onRadRescus(IsUtilUid.isUid(), phone, address, detail, vehicle_type + "", "", tid,lngg,latt);
                                        presenter.onRadRescus(uid, phone, address, detail, vehicle_type + "", "", tid,lngg.equals("")?lng+"":lngg,latt.equals("")?lat+"":latt);
                                    }
                                } catch (JSONException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }
                            }
                        }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError arg0) {
                        // TODO Auto-generated method stub
                        ByAlert.alert(arg0);
                        closeProgressDialog();
                    }
                }, "image[]", files, params);
                MyApplcation.addRequest(multipartRequest);

                break;
        }
    }

    public String isDid(String cityCode) {
        cityCodeId = cityCode;
        return cityCodeId;
    }

    /**
     * 显示车型
     * @param beans
     * @param i
     */
    public void onOnSpinerTwo(WeiXiuBeans beans, int i) {

        spinner21.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            // parent： 为控件Spinner view：显示文字的TextView position：下拉选项的位置从0开始
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                vehicle_type = weixiubean.getVehicle_type().get(position).getId();
            }

            //没有选中时的处理
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
    }
    private int onTime=0;
    TimerTask task = new TimerTask() {
        @Override
        public void run() {
            try {
                ((Activity)getActivity()).runOnUiThread(new Runnable() {      // UI thread
                    @Override
                    public void run() {
                        onTime++;
                        wait_tv.setText("已等待:" + MyTimerFormat.ChangeToTime(shicha + onTime) + "");
                    }
                });
            }catch (Exception e){

            }

        }
    };

    private void timeCount() {
        try {
            timer.schedule(task, 0, 1000);
        } catch (Exception e) {
        }
    }


    @Override
    public void update(Observable observable, Object data) {
        ResultEntity entity = handlerError(data);
        if (entity != null) {
            IsUtilUid.tianjia(entity);
            //参数
            if (entity.getEventType() == presenter.Repair_success) {
                weixiubean = (WeiXiuBeans) entity.getData();
                adapter = new SpingAdapter(weixiubean, getActivity());
                spinner21.setAdapter(adapter);
                onOnSpinerTwo(weixiubean, 1);

                try {
                    closeProgressDialog();
                } catch (Exception ex) {
                }
            }
            //报修
            if (entity.getEventType() == presenter.Driver_success) {
                dispatch_rel.setVisibility(View.VISIBLE);
                add_repair_rel.setVisibility(View.GONE);
                timeCount();

                Intent intent = new Intent("tvQuxiaoOrder");
                getActivity().sendBroadcast(intent);
                try {
                    closeProgressDialog();
                } catch (Exception ex) {
                }

            }
            //维修（进行中）
            if (entity.getEventType() == messgelPresenter.Repair_current_success) {
                commend_anchor_ptr.refreshComplete();//设置刷新完成
                beans = (RepairBean) entity.getData();
                if (beans.getRepair_status()==null) {
                    dispatch_rel.setVisibility(View.GONE);
                    add_repair_rel.setVisibility(View.VISIBLE);
                    busy_rel.setVisibility(View.GONE);
                }
                SPUtils.put(getActivity(), null,
                        Const.status, beans.getRepair_status());
                shicha = TimeFormat.getStampDiff(beans.getCreate_time());
                if (beans.getRepair_status().equals("0")) {
                    System.out.println(">>>>>维修0");
                    timeCount();
                    dispatch_rel.setVisibility(View.VISIBLE);
                    add_repair_rel.setVisibility(View.GONE);
                    busy_rel.setVisibility(View.GONE);
                    Intent intent = new Intent("tvQuxiaoOrder");
                    getActivity().sendBroadcast(intent);

                } else if (beans.getRepair_status().equals("1")) {
                    System.out.println(">>>>>维修中");
                    DriverRepair.getInstance().tvQuxiaoOrder.setVisibility(View.GONE);
                    dispatch_rel.setVisibility(View.GONE);
                    add_repair_rel.setVisibility(View.GONE);
                    busy_rel.setVisibility(View.VISIBLE);
                    tvwerwerwerwer.setText("您的维修订单正在进行中...");
                    null_order_img.setBackgroundResource(R.drawable.order_mangsb);
                } else if (beans.getRepair_status().equals("2") || beans.getRepair_status().equals("3") || beans.getRepair_status().equals("4") || beans.getRepair_status().equals("5")) {
//                    System.out.println(">>>>>维修");
                    System.out.println(">>>>>维修2345");
                    busy_rel.setVisibility(View.VISIBLE);
                    add_repair_rel.setVisibility(View.GONE);
                    dispatch_rel.setVisibility(View.GONE);
                } else if (beans.getRepair_status().equals("9")) {

                    System.out.println(">>>>>维修9");
                    dispatch_rel.setVisibility(View.GONE);
                    add_repair_rel.setVisibility(View.VISIBLE);
                    busy_rel.setVisibility(View.GONE);
                }
            }
        }
        try {
            closeProgressDialog();
        } catch (Exception e) {
            // TODO: handle exception
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ImageSelector.IMAGE_REQUEST_CODE && resultCode == RESULT_OK && data != null) {
            List<String> pathList = data.getStringArrayListExtra(ImageSelectorActivity.EXTRA_RESULT);
            for (String path : pathList) {
                Log.i("ImagePathList", path);
                if (listImg.size() < 3) {
                    String localSelectPath01 = ImageCompress.compress(path);
                    listImg.add(localSelectPath01);
                }
            }
        }else if (requestCode == 108) {
            if(data!=null){
                address_tv.setText(data.getStringExtra("address"));
                lngg= data.getStringExtra("lngg");
                latt= data.getStringExtra("latt");
            }
        }
    }

    /**
     * gridView适配器
     */
    public class GridAdapter extends BaseAdapter {
        private LayoutInflater inflater; // 视图容器
        private int selectedPosition = -1;// 选中的位置
        private boolean shape;

        public boolean isShape() {
            return shape;
        }

        public void setShape(boolean shape) {
            this.shape = shape;
        }

        public GridAdapter(Context context) {
            inflater = LayoutInflater.from(context);
        }

        public int getCount() {
            return (listImg.size() + 1);
        }

        public Object getItem(int arg0) {

            return null;
        }

        public long getItemId(int arg0) {

            return 0;
        }

        public void setSelectedPosition(int position) {
            selectedPosition = position;
        }

        public int getSelectedPosition() {
            return selectedPosition;
        }

        /**
         * ListView Item设置
         */
        public View getView(int position, View convertView, ViewGroup parent) {
            final int coord = position;
            ViewHolder holder = null;
            if (convertView == null) {

                convertView = inflater.inflate(R.layout.item_published_grida,
                        parent, false);
                holder = new ViewHolder();
                holder.image = (ImageView) convertView
                        .findViewById(R.id.item_grida_image);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            if (position == listImg.size()) {
                holder.image.setImageBitmap(BitmapFactory.decodeResource(
                        getResources(), R.drawable.icon_addpic_unfocused));
                if (position == 3) {
                    holder.image.setVisibility(View.GONE);
                }
            } else {
                XImageLoader.load("file://" + listImg.get(position),
                        holder.image);
            }

            return convertView;
        }

        public class ViewHolder {
            public ImageView image;
        }
    }
    /**
     * 打开图库
     */
    private void pic() {
        ImageConfig imageConfig
                = new ImageConfig.Builder(new GlideLoader())
                .steepToolBarColor(getResources().getColor(R.color.blue))
                .titleBgColor(getResources().getColor(R.color.blue))
                .titleSubmitTextColor(getResources().getColor(R.color.white))
                .titleTextColor(getResources().getColor(R.color.white))
                // 开启多选   （默认为多选）
                .mutiSelect()
                // 多选时的最大数量   （默认 9 张）
                .mutiSelectMaxSize(3)
                // 开启拍照功能 （默认关闭）
                .showCamera()
                // 已选择的图片路径
                // .pathList(path)
                // 拍照后存放的图片路径（默认 /temp/picture） （会自动创建）
                .filePath("/ImageSelector/Pictures")
                .build();

        ImageSelector.open(con, imageConfig);   // 开启图片选择器
    }
}
